<script setup lang="ts">
// 从Vue中导入ref、onMounted和computed函数
import {ref, onMounted, computed, getCurrentInstance} from "vue";
// 从vue-router中导入useRoute函数，用于获取当前路由信息
import { useRoute } from "vue-router";
// 从Stripe库中导入loadStripe函数，用于加载Stripe对象
import { loadStripe } from "@stripe/stripe-js";
// 导入自定义的消息组件SrMessages
import SrMessages from "./SrMessages.vue";
import {ElButton, ElCard, ElDivider, ElIcon} from "element-plus";
import {useRouter} from "vue-router";
import {getOrderDetail} from "@/api/orderList.ts";
import {getSetting} from "@/api/index.ts";
import {Local, Session} from "@/utils/storage.ts";
import { useCurrencyStore } from '@/pinia/currency'
import {getCarts} from "@/api/details.ts";
import {useCartStore} from "@/pinia/cart.ts";
import mitt from '@/utils/mitt.ts'
import DateFormatter from '@/components/common/DateFormatter.vue'

const currencyStore = useCurrencyStore()
const cartStore = useCartStore()
const { proxy } = getCurrentInstance()
const fullscreenLoading = ref(false)
const openFullScreen1 = () => {
  fullscreenLoading.value = true
  setTimeout(() => {
    fullscreenLoading.value = false
  }, 2000)
}
const router = useRouter()

const props = defineProps({
  // 定义一个名为currency的prop，类型为字符串，默认值为'usd'
  clientSecret: {
    type: String,
    default: '',
  }
})

// 订单数据类型
interface OrderData {
  orderId: number
  orderNo: string
  amount: number
  payTime: string
  estimatedDelivery: string
  paySuccess: string
  payStatus: number
}

// 模拟订单数据
const orderData = ref<OrderData>({
  orderNo: '',
  amount: 0,
  payTime: '',
  estimatedDelivery: '',
  paySuccess: '',
  payStatus: null,
  orderId: null
})

const showTips = ref(false)
const handleViewOrder = () => {
  router.push({name: 'orderDetails',query: {id: Local.get('orderId')}})
}

const handleBackHome = () => {
  window.location.href = '/home/clothings.html';
  // router.push({name: 'index',query:{id:2}})
}

// 支付失败
const paymentFailed = ref(true)
const handleRepay = () => {
  router.push({
    name: 'order',
    query: {
      payment_failed: 1,
      orderId: orderData.value.orderId,
      amount: orderData.value.amount
    }
  })
}

// 定义一个响应式变量messages，用于存储消息
const messages = ref([]);
const payStatus = ref<string | null>(null);
// 定义一个响应式变量clientSecret，用于存储支付意图的客户端密钥
const clientSecret = ref('');

// 使用computed计算属性获取当前路由的查询参数
const currentRoute = computed(() => {
  return useRoute().query;
});
// 从当前路由的查询参数中提取payment_intent_client_secret，并赋值给clientSecret
// clientSecret.value = props.clientSecret?.payment_intent_client_secret;

// 声明一个变量stripe，用于存储Stripe对象
let stripe;
const siteKey = ref('')
//获取网站密钥
const getSiteKey = async () => {
  const res = await getSetting();
  if (res.code === 200) {
    siteKey.value = res.result.stripe_pay_key;
    Local.set('settingConfig', res.result)
  }
}
// 使用onMounted生命周期钩子，在组件挂载时执行异步操作
onMounted(async () => {
  openFullScreen1()
  clientSecret.value = Session.get('clientSecret')
  // 从后端获取publishableKey，用于初始化Stripe
  if (!Local.get('settingConfig')) {
    await getSiteKey();
  }else{
    siteKey.value = Local.get('settingConfig').stripe_pay_key
  }

  const publishableKey =  siteKey.value;
  // 使用publishableKey加载Stripe对象
  stripe = await loadStripe(publishableKey);

  // 使用Stripe对象的retrievePaymentIntent方法获取支付意图信息
  const {error, paymentIntent} = await stripe.retrievePaymentIntent(
      clientSecret.value,
  );

  // 如果获取支付意图时发生错误，将错误信息推入messages数组
  if (error) {
    messages.value.push(error.message);
  }
  // 将支付意图的状态和ID信息推入messages数组
  messages.value.push(`Payment ${paymentIntent.status}: ${paymentIntent.id}`)

  payStatus.value = paymentIntent.status

  getOrderDetails()

  getCartListApi()
});

const getOrderDetails = async () => {
  const res = await getOrderDetail(Local.get('orderId'))
  if (res.code === 200) {
    orderData.value.orderNo = res.result.order_no
    orderData.value.amount = res.result.pay_price
    orderData.value.payTime = res.result.pay_time
    orderData.value.payStatus = res.result.pay_status
    orderData.value.orderId = res.result.id
  }
}
const getCartListApi = async () => {
  await getCarts().then((res) => {
    if (res.code === 200) {
      cartStore.setShopCart(res.result)
      mitt.emit('getCartList')
    }
  })
}
</script>

<template>
<!--  <body>-->
<!--  <main>-->
<!--    &lt;!&ndash; 返回主页的链接 &ndash;&gt;-->
<!--    <a href="/">home</a>-->
<!--    &lt;!&ndash; 显示感谢信息 &ndash;&gt;-->
<!--    <h1>Thank you!</h1>-->
<!--    &lt;!&ndash; 使用SrMessages组件显示支付相关的消息 &ndash;&gt;-->
<!--    <sr-messages-->
<!--        v-if="clientSecret"-->
<!--        :messages="messages"-->
<!--    />-->
<!--  </main>-->
<!--  </body>-->
  <div class="success-container" v-loading="fullscreenLoading">
    <!--  页面标题Order Complete  -->
    <div class="page-title">Order Complete</div>
    <div class="decorative-strip"></div>
    <el-card class="success-card">
      <!-- 加载中状态 -->
      <div v-if="payStatus === null" class="loading-state">
        <p>Loading payment status...</p>
      </div>
      <!-- 成功标识区 -->
      <div class="success-header" v-else-if="payStatus == 'succeeded'">
        <el-icon class="success-icon">
          <svg width="60" height="60" viewBox="0 0 48 48" fill="none">
            <path d="M24 44C35.0457 44 44 35.0457 44 24C44 12.9543 35.0457 4 24 4C12.9543 4 4 12.9543 4 24C4 35.0457 12.9543 44 24 44Z"
                  stroke="#333" stroke-width="3" stroke-linecap="round"/>
            <path d="M16 24L22 30L34 18"
                  stroke="#333"
                  stroke-width="3"
                  stroke-linecap="round"
                  stroke-linejoin="round"/>
          </svg>
        </el-icon>
<!--        <h1 class="title">支付成功</h1>-->
        <p class="subtitle">Payment Successful</p>
      </div>

      <!--   失败标识区   -->
      <div class="failure-header" v-else>
<!--        <h1 class="title">支付失败</h1>-->
        <p class="subtitle">Payment Failed</p>
        <p v-if="orderData.payStatus == 1">Payment to be made</p>
      </div>

      <!-- 核心信息展示 -->
      <div class="info-section" v-if="payStatus == 'succeeded'">
        <div class="info-row">
          <span class="label">Order Number：</span>
          <span class="value">{{ orderData.orderNo }}</span>
        </div>
        <el-divider border-style="dashed" />

        <div class="info-row">
          <span class="label">Payment amount：</span>
          <span class="value highlight">{{ currencyStore.currentCurrency.unit }} {{ proxy.$ConvertPrice(orderData.amount) }}</span>
        </div>
        <el-divider border-style="dashed" />

        <div class="info-row">
          <span class="label">Payment Time：</span>
          <span class="value"><DateFormatter :value="orderData.payTime" format="MM/DD/YYYY HH:mm:ss" /></span>
        </div>
      </div>

      <!-- 下一步操作 -->
      <div class="action-btns" v-if="payStatus == 'succeeded'">
        <el-button
            type="primary"
            class="black-btn"
            @click="handleViewOrder">
          View order details
        </el-button>
        <el-button
            class="ghost-btn"
            @click="handleBackHome">
          Back to Home
        </el-button>
      </div>
      <div class="action-btns" v-else>
        <el-button
            class="repay-btn"
            @click="handleRepay">
          Repay
        </el-button>
      </div>
    </el-card>

    <!-- 物流提示 -->
    <!--    <transition name="el-fade-in">-->
    <!--      <div v-if="showTips" class="logistics-tips">-->
    <!--        <el-icon><Box /></el-icon>-->
    <!--        订单预计清关时间3-5个工作日-->
    <!--      </div>-->
    <!--    </transition>-->
  </div>
</template>
<style lang="scss" scoped>
.success-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  padding: 40px 20px;
  position: relative;

  .page-title {
    text-align: center;
    font-size: 36px;
    color: #333;
    margin-bottom: 40px;
  }

  .decorative-strip {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 8px;
    background: repeating-linear-gradient(
            45deg,
            #000,
            #000 15px,
            transparent 15px,
            transparent 30px
    );
  }
}

.success-card {
  max-width: 680px;
  margin: 0 auto;
  border: 2px solid #000;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);

  :deep(.el-card__body) {
    padding: 40px;
  }
}

.success-header {
  text-align: center;
  margin-bottom: 40px;

  .success-icon {
    animation: checkmark 0.6s ease;
  }

  .title {
    font-size: 32px;
    color: #333;
    margin: 20px 0 8px;
    font-weight: 500;
  }

  .subtitle {
    font-size: 16px;
    color: #666;
    letter-spacing: 2px;
  }
}

.failure-header {
  text-align: center;
  margin-bottom: 40px;

  .failure-icon {
    animation: checkmark 0.6s ease;
  }

  .title {
    font-size: 32px;
    color: #d41818;
    margin: 20px 0 8px;
    font-weight: 500;
  }

  .subtitle {
    font-size: 16px;
    color: #d41818;
    letter-spacing: 2px;
  }
}

.info-section {
  margin: 30px 0;

  .info-row {
    display: flex;
    justify-content: space-between;
    padding: 18px 0;

    .label {
      color: #666;
      font-size: 16px;
    }

    .value {
      color: #333;
      font-weight: 500;

      &.highlight {
        font-size: 24px;
        letter-spacing: 1px;
      }
    }
  }
}

.action-btns {
  margin-top: 40px;
  text-align: center;

  .black-btn {
    background: #000;
    border-color: #000;
    padding: 12px 36px;
    font-size: 16px;

    &:hover {
      background: #333;
    }
  }

  .ghost-btn {
    border-color: #000;
    color: #000;
    margin-left: 20px;
    padding: 12px 36px;

    &:hover {
      background: rgba(0,0,0,0.05);
    }
  }

  .repay-btn {
    background: #d41818;
    border-color: #d41818;
    color: #FFFFFF;
    margin-left: 20px;
    padding: 12px 36px;

    &:hover {
      background-color: #d41818;
    }
  }
}

.logistics-tips {
  text-align: center;
  margin-top: 30px;
  color: #666;
  font-size: 14px;

  .el-icon {
    vertical-align: middle;
    margin-right: 8px;
  }
}

@keyframes checkmark {
  0% { transform: scale(0); opacity: 0; }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); opacity: 1; }
}
</style>
